package com.yiwei.hdb.util;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.widget.ImageView;

/**
 * 圆形、圆角图标工具
 *
 * Created by caishenglang on 2016/12/6.
 */

public class RoundedBitmapUtils {

    private static Bitmap createSquareBitmap(Bitmap bitmap) {
        Bitmap squareBitmap;
        if (bitmap.getWidth() >= bitmap.getHeight()){
            squareBitmap = Bitmap.createBitmap(bitmap,bitmap.getWidth()/2-bitmap.getHeight()/2,0,bitmap.getHeight(),bitmap.getHeight());
        }else {
            squareBitmap = Bitmap.createBitmap(bitmap,bitmap.getHeight()/2-bitmap.getWidth()/2,0,bitmap.getWidth(),bitmap.getWidth());
        }
        return squareBitmap;
    }

    public static void setRoundedDrawable(Resources resources, ImageView imageView, int id){
        Bitmap bitmap = BitmapFactory.decodeResource(resources, id); //获取Bitmap图片
        setRoundedDrawable(resources,imageView,bitmap);
    }

    public static void setRoundedDrawable(Resources resources, ImageView imageView, Bitmap bitmap){
        Bitmap squareBitmap = createSquareBitmap(bitmap);
        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, squareBitmap);
        roundedBitmapDrawable.setCircular(true);
        imageView.setImageDrawable(roundedBitmapDrawable);
    }

    public static void setCornerRadiusDrawable(Resources resources, ImageView imageView, int id, float radius){
        Bitmap bitmap = BitmapFactory.decodeResource(resources, id);
        setCornerRadiusDrawable(resources,imageView,bitmap,radius);
    }

    public static void setCornerRadiusDrawable(Resources resources, ImageView imageView, Bitmap bitmap, float radius){
        Bitmap squareBitmap = createSquareBitmap(bitmap);
        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, squareBitmap);
        roundedBitmapDrawable.setCornerRadius(radius);
        imageView.setImageDrawable(roundedBitmapDrawable);
    }
}
